// 指标框架制定
<template>
  <div class="box1">

    <div class="scroll-notification" :class="{ active: showNotification }">
      <span>{{ notification }}</span>
      <button class="close-button">X</button>
    </div>
    年份：&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
    <el-input-number
      v-model="year"
      controls-position="right"
      @change="handleChange"
      :min="2020"
      :max="2024"
      class="yearw"
    ></el-input-number>
    <br />
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5" style="margin-top: 20px">
        <el-button type="success" size="mini" icon="el-icon-plus" style="margin-right: 20px" plain
          @click="handleAdd">新增</el-button>
        <el-button size="mini" type="info" icon="el-icon-edit" plain style="margin-right: 20px"
          @click="handleUpdate">编辑</el-button>
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['traget:enact:export']" style="margin-right: 20px">导出</el-button>
        <el-button icon="el-icon-d-arrow-right" type="primary" style="margin-right: 20px" size="mini" plain
          @click="issue">下发</el-button>
        <el-button size="mini" style="margin-right: 20px" type="danger" icon="el-icon-delete" plain
          @click="handleDelete">删除</el-button>
      </el-col>
    </el-row>
    <el-table ref="dataTable" :data="list" style="width: 96%" text-align="center" :span-method="arraySpanMethod" border
      @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column prop="onestep_substance" label="一级指标" align="center" width="300"></el-table-column>
      <el-table-column prop="twostep_substance" label="二级指标" align="center"></el-table-column>
      <el-table-column prop="signfor_times" label="签收时限" align="center" width="220"></el-table-column>
      <el-table-column prop="state_issue" label="下发状态" align="center" width="218"></el-table-column>
    </el-table>
    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body>
      <el-form ref="tableData" :model="tableData" :rules="rules" label-width="130px">
        <el-form-item label="一级指标" prop="onestep_substance">
          <el-select v-model="tableData.onestep_substance" placeholder="请选择一级指标" :disabled="title === '修改'">
            <el-option v-for="option in oneIndexOptions" :key="option" :label="option" :value="option"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="二级指标" prop="twostep_substance">
          <el-input v-model="tableData.twostep_substance" placeholder="请输入二级指标" />
        </el-form-item>
        <el-form-item label="签收时限" prop="signfor_times">
          <el-input v-model="tableData.signfor_times" placeholder="请输入签收时限" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { apply, add, update, dele, updatestate, getYear } from "../../../api/zhenfu/index";

export default {
  data() {
    return {
      year: new Date().getFullYear(),
      list: [],
      tableData: {
        twostep_id: "",
        twostep_id:"",
        onestep_substance: "",
        twostep_substance: "",
        signfor_times: "",
        state_issue: ""

      },
      showNotification: false,
      notification: '军爷别发呆了...',
      open: false,
      title: "",

      //弹出框
      rules: {
        onestep_substance: [
          { required: true, message: "一级指标不能为空", trigger: "blur" },
        ],
        twostep_substance: [
          { required: true, message: "二级指标不能为空", trigger: "blur" },
        ],
        signfor_times: [
          { required: true, message: "签收时间不能为空", trigger: "blur" },
        ],
      },
      oneIndexOptions: [],
      selectedRows: [],
    };
  },
  created() {
    this.fetchData();
  },

  methods: {
    // 年份变化处理
    handleChange(value) {
      console.log("Year changed to:", value); // 确保这里打印了正确的值
      this.createdDate = value;
      console.log("Calling fetchDataByYear with:", value);
      this.fetchDataByYear(value); // 确保这里调用了 fetchDataByYear
    },

    // 根据年份获取数据
    fetchDataByYear(createdDate) {
      console.log("fetchDataByYear called with createdDate:", createdDate);
      console.log("Fetching data for year:", createdDate); // 调试输出
      getYear({ createdDate }).then((res) => {
        console.log("API Response:", res); // 调试输出
        const messageData = res.result ? res.result.message : res.message;
        if (messageData) {
          const listData = JSON.parse(messageData);
          this.list = listData.map(item => ({
            twostep_id: item.twostep_id,
            onestep_substance: item.onestep_substance,
            twostep_substance: item.twostep_substance,
            signfor_times: item.signfor_times,
            state_issue: item.state_issue
          }));
          this.oneIndexOptions = [...new Set(listData.map(item => item.onestep_substance))];
        } else {
          console.log("messageData is undefined");
        }
      }).catch((err) => {
        console.log("ERROR:", err);
      });
    },
    // 渲染数据
    fetchData() {
      apply().then((res) => {
        const messageData = res.result ? res.result.message : res.message;

        if (messageData) {
          const listData = JSON.parse(messageData);

          // 按一级指标排序
          this.list = listData.map(item => ({
            id: item.twostep_id,
            twostep_id: item.twostep_id,
            onestep_substance: item.onestep_substance,
            twostep_substance: item.twostep_substance,
            signfor_times: item.signfor_times,
            state_issue: item.state_issue
          }));
          this.oneIndexOptions = [...new Set(this.list.map(item => item.onestep_substance))];
        } else {
          console.log("messageData is undefined");
        }
      })
        .catch((err) => {
          console.log(err);
        });
    },
    startNotification() {
      this.showNotification = true;
      setTimeout(() => {
        this.showNotification = false;
      }, 5000); // 持续时间，5秒后消失
    },
    addCloseButtonListener() {
      document.addEventListener('DOMContentLoaded', () => {
        const closeButton = document.querySelector('.close-button');
        closeButton.addEventListener('click', () => {
          const notification = closeButton.closest('.scroll-notification');
          notification.remove();
        });
      });
    },
    // 处理选择变化
    handleSelectionChange(val) {
      this.selectedRows = val;
    },
    // 年份变化处理
    handleChange(value) {
      console.log("Year changed to: ", value);
      // 这里可以添加你希望在年份改变时执行的逻辑
    },
    // 点击新增
    handleAdd() {
      this.open = true;
      this.title = "新增";
      this.num = 1;
      this.tableData = {
        onestep_substance: "",
        twostep_substance: "",
        signfor_times: "",
      };
    },
    // 点击编辑
    handleUpdate() {
      if (this.selectedRows.length === 1) {
        const item = this.selectedRows[0];
        this.open = true;
        this.title = "修改";
        this.tableData = {
          twostep_id: item.id,
          twostep_id: item.twostep_id,
          onestep_substance: item.onestep_substance || "",  // 确保赋值时不为null
          twostep_substance: item.twostep_substance || "",  // 确保赋值时不为null
          signfor_times: item.signfor_times || "",  // 确保赋值时不为null
          state_issue: item.state_issue || "未下发", // 确保赋值时不为null
          state_issue: item.state_issue
        };
      } else {
        this.$message.error("请选择一条记录进行编辑");
      }
    },

    // 提交表单
    submitForm() {
      this.$refs.tableData.validate((valid) => {
        if (valid) {
          console.log("提交数据：", this.tableData);

          // 检查必填字段
          if (!this.tableData.signfor_times || this.tableData.signfor_times.trim() === "") {
            this.$message.error("签收时限不能为空");
            return;
          }

          const data = {
            twostep_id: this.tableData.twostep_id,
            onestep_substance: this.tableData.onestep_substance,
            twostep_substance: this.tableData.twostep_substance,
            signfor_times: this.tableData.signfor_times,
            state_issue: this.tableData.state_issue

          }
          // 判断是新增还是编辑
          if (this.title === "新增") {
            add(data)
              .then((res) => {
                this.$message.success("新增成功");
                this.fetchData();
                this.open = false;
              })
              .catch((err) => {
                this.$message.error("新增失败");
                console.error("新增失败:", err);
              });
          } else if (this.title === "修改") {
            update(data)
              .then((res) => {
                this.$message.success("修改成功");
                this.fetchData();
                this.open = false;
                console.log(res);
              })
              .catch((err) => {
                console.error("修改失败:", err);
                this.$message.error("修改失败: " + (err.message || "系统未知错误"));
              });
          }
        }
      });
    },
    // 合并单元格
    arraySpanMethod({ row, column, rowIndex, columnIndex }) {
      if (columnIndex === 1) {
        const onestep_substance = row.onestep_substance;
        const prevRow = this.list[rowIndex - 1];
        let rowSpan = 1;

        if (prevRow && prevRow.onestep_substance === onestep_substance) {
          return [0, 0];
        }

        for (let i = rowIndex + 1; i < this.list.length; i++) {
          if (this.list[i].onestep_substance === onestep_substance) {
            rowSpan++;
          } else {
            break;
          }
        }

        return [rowSpan, 1];
      }
    },

    // 点击删除
    handleDelete() {
      if (this.selectedRows.length > 0) {
        this.$confirm("确定删除选中的数据吗？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(async () => {
            try {
              const twoIndexes = this.selectedRows.map((row) => ({
                twostep_substance: row.twostep_substance
              })); // 构造符合后端需求的对象数组
              console.log("二级指标：", twoIndexes); // 打印二级指标内容
              await Promise.all(
                twoIndexes.map(async (zhiBiao) => {
                  await dele(zhiBiao);
                })
              );
              this.$message.success("删除成功");
              this.fetchData(); // 重新获取数据
            } catch (err) {
              console.error("删除失败:", err);
              this.$message.error("删除失败");
            }
          })
          .catch(() => {
            this.$message.info("已取消删除");
          });
      };
    },
    // 下发数据
    async issue() {
      if (this.selectedRows.length > 0) {
        this.$confirm("确定下发选中的数据吗？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(async () => {
            try {
              this.$loading({ // 添加加载动画
                lock: true,
                text: '正在下发...',
                spinner: 'el-icon-loading',
                background: 'rgba(0, 0, 0, 0.7)'
              });
              // 构建要删除的数据对象
              const xiafaPromises = this.selectedRows.map(row => {
                // 传递整个对象，而不是属性
                return updatestate({
                  twostep_id: row.twostep_id, // 确保 ID 是正确传递的
                  onestep_substance: row.onestep_substance,
                  twostep_substance: row.twostep_substance,
                  signfor_times: row.signfor_times,
                  state_issue: row.state_issue,
                });
              });
              await Promise.all(xiafaPromises);
              this.$message.success("下发成功");
              this.fetchData(); // 重新获取数据
            } catch (err) {
              console.error("下发失败:", err);
              this.$message.error("下发失败");
            } finally {
              this.$loading().close(); // 关闭加载动画
            }
          })
          .catch(() => {
            this.$message.info("已取消下发");
          });
      } else {
        this.$message.error("请至少选择一条记录进行下发");
      }
    },
    // 导出数据
    handleExport() {
      this.download('traget/enact/export', {
        ...this.queryParams
      }, `enact_${new Date().getTime()}.xlsx`)
    },
    // 取消弹框
    cancel() {
      this.open = false;
    },
  },
  mounted() {
    this.startNotification();
    // 如果需要定期显示，可以设置定时器
    setInterval(this.startNotification, 10000); // 每10秒显示一次

    this.addCloseButtonListener();
  }

};
</script>

<style scoped>
.el-dialog {
  width: 40% !important;
}

.box1 {
  width: 100%;
  height: 100%;
  margin-left: 30px;
  margin-top: 20px;
}

.el-input--small .el-input__inner {
  width: 70%;
}

.bth {
  float: right;
  margin-top: -30px;
  margin-left: -30px;
}

.scroll-notification {
  position: fixed;
  top: 0;
  left: 0;
  width: 200px;
  /* 增加宽度 */
  padding: 0 1rem;
  /* 添加内边距 */
  background-color: #ffcbcb;
  color: rgb(121, 109, 109);
  line-height: 30px;
  height: 30px;
  overflow: hidden;
  white-space: nowrap;
  animation: scrollText 10s linear infinite;
  /* 减少动画时长 */
  border-radius: 0 0 5px 5px;
  /* 添加圆角 */
}

.close-button {
  position: absolute;
  right: 5px;
  top: 50%;
  transform: translateY(-50%);
  background: none;
  border: none;
  color: white;
  font-size: 16px;
  cursor: pointer;
}

.scroll-notification:hover {
  animation-play-state: paused;
}

@keyframes scrollText {
  0% {
    transform: translateX(100vw);
    /* 使用transform替代translateX */
  }

  100% {
    transform: translateX(-100%);
  }
}
</style>